
Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}
var user_info = null;
function loginStatus() {
    let userInfo = $.cookie("user_info")
    if (userInfo !== undefined) {
        userInfo = JSON.parse(userInfo)
        user_info=userInfo
        $("#loginBtn").css("display", "none")
        $("#regBtn").css("display", "none")
        $("#myCenterBtn").removeClass("d-none")
        $("#exitBtn").removeClass("d-none")
        $("#userTx").text(userInfo["name"].substring(0, 1))
    } else {
        $("#loginBtn").css("display", "block")
        $("#regBtn").css("display", "block")
        $("#myCenterBtn").addClass("d-none")
        $("#exitBtn").addClass("d-none")
        $("#exitBtn").removeClass("d-flex")
    }
}
var ip_host = window.location.host
var book_intro_href = "#book_intro"
var book_sheet_href = "#book_sheet"
var index_href = "#"
var curPage = 0; // 1 代表个人中心页
if (window.location.href.search("userArea") !== -1) {
    book_intro_href = "../index.html#book_intro"
    book_sheet_href = "../index.html#book_sheet"
    index_href = "../index.html"
    curPage = 1
}
var page_head = `    
    <div class="navbar-box">
        <nav class="navbar navbar-expand-md navbar-light bg-transparent w-100">
            <div class="container-fluid">
                <a class="navbar-brand" href="#">
                    <i class="iconfont icon-tushu"></i>
                    图书管理系统
                </a>
                <button aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation"
                        class="navbar-toggler" data-target="#navbarNavDropdown" data-toggle="collapse"
                        type="button">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarNavDropdown">
                    <ul class="navbar-nav">
                        <li class="nav-item">
                            <a aria-current="page" class="nav-link" href="${index_href}">首页</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="${book_intro_href}">图书推荐</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="${book_sheet_href}">图书搜索</a>
                        </li>
                    </ul>
                    <div class="user-action-box">
                        <ul class="navbar-nav">
                            <li class="nav-item" id="loginBtn">
                                <a class="nav-link" data-target="#user_login" data-toggle="modal">登录</a>
                            </li>
                            <li class="nav-item" id="regBtn">
                                <a class="nav-link" data-target="#user_register" data-toggle="modal">注册</a>
                            </li>
                            <li class="nav-item d-none" id="myCenterBtn">
                                <a class="nav-link">
                                    <!--                                    <i class="iconfont icon-project_space mr-1"></i>-->
                                    <span id="userTx"></span>个人中心</a>
                            </li>
                            <li class="nav-item d-flex d-none align-items-center justify-content-center" id="exitBtn">
                                <a class="nav-link text-danger"><i
                                        class="iconfont icon-tuichu_exit mr-1"></i>退出</a>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </nav>
    </div>
`
$("#page_head").html(page_head)
loginStatus()
$("#exitBtn").on('click', function () {
    $.removeCookie('user_info', {domain: 'localhost', path: '/'})
    console.log("退出", $.cookie("user_info"));
    if (curPage == 1) {
        location.href = "../index.html"
    } else {
        loginStatus()
    }
})

// ajax 配置
$.ajaxSetup({
    beforeSend() {
        console.log("发送请求")
        if (user_info !== null) {
            let data = arguments[1].data
            console.log(arguments)
            let method = arguments[1].type
            let url = arguments[1].url
            let newData = ""
            let usr = "&uid=" + hex_md5(user_info["id"] + user_info["phone"]) + "&usr=" + user_info["id"]
            if (method == "GET") {
                arguments[1].url = url + usr
            } else if (method == "POST") {
                arguments[1].data = data + usr
            }
        }
        let mask = document.getElementById("my-mask")
        if (mask == null) {
            let div = document.createElement("div")
            let obj = $(div)
            obj.attr("id", "my-mask")
            obj.css({
                "background": "rgba(0,0,0,0.3)",
                "position": "fixed",
                "top": "0",
                "left": "0",
                "width": "100%",
                "height": "100%",
                "display": "flex",
                "align-items": "center",
                "justify-content": "center",
                "color": "white",
                "font-size": "1.20rem",
                "font-weight": "600",
                "z-index": "9999"
            })
            obj.html("数据加载中...")
            $("body").append(div)
        } else {
            mask.style.display = "flex"
        }
    },
    complete(xhr) {
        if (xhr.responseJSON.code == 10006) {
            alert("无权访问");
            console.log("无权访问");
        }
        // for (var t = Date.now(); Date.now() - t <= 1000;) ;
        let mask = document.getElementById("my-mask")
        mask.style.display = "none"
    }
});


// 非空判断
function required(val) {
    if (val == undefined || val == "" || val == null) {
        return false;
    }
    return true;
}

// 长度检测
function hasLen(min, max, val) {
    len = val.length
    if (required(val)) {
        if (len >= min && len <= max) {
            return true
        }
    }
    return false
}

function isPoneAvailable(str) {
    var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
    if (!myreg.test(str)) {
        return false;
    } else {
        return true;
    }
}

// 获取单用户信息
function getUser(id) {
    let singleUser
    $.ajax({
        url: "http://localhost:8080/reader",
        data: {
            key: "getReaderById",
            id: id
        },
        method: "post",
        async: false, // 同步
        success(data) {
            console.log(data)
            if (data.code === 10001) {
                singleUser = data.data
            }
        },
        error(XMLHttpRequest, textStatus, errorThrown) {
            console.log("ajax 请求失败");
        }
    })
    return singleUser
}

// 二维码生成
function qrcode(id, content) {
    $("#" + id).qrcode({
        render: "canvas",
        width: 180,
        height: 180,
        text: content
    })
}

// 参数检验
function check(formData) {
    let phone = formData["phone"]
    let stdId = formData["stdId"]
    let pwd = formData["pwd"]
    let college = formData["college"]
    let prof = formData["prof"]
    let name = formData["name"]
    let email = formData["email"]
    if (!required(name)) {
        console.log("名字必须");
        alert("名字必须")
        return false
    }
    if (!required(email)) {
        console.log("邮箱必须");
        alert("邮箱必须")
        return false
    }
    if (college == 0) {
        console.log("请选择学院")
        alert("请选择学院")
        return false
    }
    if (prof == 0) {
        console.log("请选择专业")
        alert("请选择专业")
        return false
    }
    if (!isPoneAvailable(phone)) {
        // 手机号不符合
        console.log("手机号不符合")
        alert("手机号不符合")
        return false;
    }
    if (!hasLen(10, 10, stdId)) {
        console.log("学号长度不符合")
        alert("学号长度不符合")
        return false;
    }
    console.log(pwd)
    if (!hasLen(5, 16, pwd)) {
        alert("密码长度不符合")
        console.log("密码长度不符合")
        return false;
    }
    return true;
}

var collegeData = []
// 获取学院信息
function getCollege() {
    if (collegeData.length > 0) {
        return collegeData
    }
    $.ajax({
        url: "http://localhost:8080/college",
        data: {
            key: "getCollegeList"
        },
        method: "post",
        async: false, // 同步
        success(data) {
            console.log(data)
            if (data.code === 10001) {
                collegeData = data.data
            }
        },
        error(XMLHttpRequest, textStatus, errorThrown) {
            console.log("ajax 请求失败");
        }
    })
    return collegeData
}

var profData = []

// 根据cid 获取专业
function getProf(cid) {
    $.ajax({
        url: "http://localhost:8080/college",
        data: {
            key: "getProfList",
            cid: cid
        },
        method: "post",
        async: false,
        success(data) {
            if (data.code === 10001) {
                profData = data.data
            }
        },
        error(XMLHttpRequest, textStatus, errorThrown) {
            console.log("ajax 请求失败");
        }
    })
    return profData
}

var allProf = []

// 获取所有专业
function getAllProf() {
    if (allProf.length > 0) {
        return allProf
    }
    $.ajax({
        url: "http://localhost:8080/college",
        data: {
            key: "getProfList",
            cid: -1
        },
        method: "post",
        async: false,
        success(data) {
            if (data.code === 10001) {
                console.log("profdata", data)
                allProf = data.data
            }
        },
        error(XMLHttpRequest, textStatus, errorThrown) {
            console.log("ajax 请求失败");
        }
    })
    console.log("返回前", allProf)
    return allProf
}

var allCategory = []

function getAllCategory() {
    if (allCategory.length > 0) {
        return allCategory
    }
    $.ajax({
        url: "http://localhost:8080/book",
        data: {
            key: "allCategory",
        },
        method: "post",
        async: false,
        success(data) {
            if (data.code === 10001) {
                console.log("allCategory", data)
                allCategory = data.data
            }
        },
        error(XMLHttpRequest, textStatus, errorThrown) {
            console.log("ajax 请求失败");
        }
    })
    return allCategory
}

// 根据cid获取图书类别名称
function getCname(cid) {
    let rst = ""
    allCategory.forEach(i => {
        if (i["cid"] == cid) {
            rst = i["cname"]
        }
    })
    return rst
}

var g_booking_list = []
var BookingList = []

// 获取预定信息列表
function getBookingList() {
    let role = user_info["roles"]
    let id = user_info["id"]
    // 在此先判断用户角色
    if (role === "user") {
        // 普通用户，查询某人的预定信息
        $.ajax({
            url:"http://localhost:8080/booking",
            async: false,
            data:{
                key: "getReaderBookingList",
                id:  id
            },
            success(data){
                BookingList = data.data
            }
        })
    } else if (role === "admin") {
        // 管理员，在此查询所有用户的预定信息
         $.ajax({
                url: "http://localhost:8080/booking",
                data: {
                    key: "getBookingList"
                },
             async: false,
                success(data) {
                    BookingList = data.data
                }
         })
    }
}

var RecordList=[]
// 获取借阅信息列表
function getBorrowingList() {
    let role = user_info["roles"]
    let id = user_info["id"]
    if (role === "user") {
        $.ajax({
            url:"http://localhost:8080/recorder",
            async: false,
            data:{
                key: "getReaderRecordList",
                id:  id
            },
            success(data){
                RecordList = data.data
            }
        })
    } else if (role === "admin") {
        $.ajax({
            url: "http://localhost:8080/recorder",
            data: {
                key: "getRecordList"
            },
            async: false,
            success(data) {
                RecordList = data.data
            }
        })
    }
}

var g_userList = []

// 获取用户信息列表
function getUserList() {
    $.ajax({
        url: "http://localhost:8080/reader",
        data: {key: "getReaderList"},
        async: false,
        success(data) {
            console.log("userdata", data);
            if (data.code === 10001) {
                g_userList = data.data
            }
        }
    })
    return g_userList
}

var g_bookList = []

// 获取图书信息列表
function getBookList() {
    let data = {
        key: "bookListAll",
    }
    $.ajax({
        url: "http://localhost:8080/book",
        data: data,
        method: "post",
        async: false,
        success(data) {
            console.log("图书信息列表", data)
            if (data.code === 10001) {
                g_bookList = data.data
            }
        },
        error(XMLHttpRequest, textStatus, errorThrown) {
            console.log("ajax 请求失败");
        }
    })
    return g_bookList
}

var g_settings = []
var logdata=[]
//获取日志维护数据
function getLoglist(){
    $.ajax({
        url: "http://localhost:8080/Logmain",
        method: "post",
        async: false,
        success(data) {
            console.log("hhhhhhh",data);
            logdata=data.data;
        },
        error(XMLHttpRequest, textStatus, errorThrown) {

            console.log("ajax 请求失败");
        }
    })
}

//隐藏按钮
function setBorrowHide(){
    $("#borrowMT").css("display","none")
}
if (user_info !== null) {
    if (curPage === 1) {
        if (user_info["roles"] === "admin") {
            getUserList()
            getBookList()
            getLoglist()
        }
        if (user_info["roles"] === "user"){
            console.log(1);
            setBorrowHide()
        }
        getBookingList()
        getBorrowingList()
    }
}

